<template>
  <q-page>
    <q-spinner v-if="loading" size="lg" color="primary" />
    <iframe v-if="htmlUrl" :src="htmlUrl" class="content-display"></iframe>
    <q-icon
      v-if="htmlUrl"
      name="download"
      color="primary"
      size="xl"
      class="download-icon"
      @click="downloadFile"
    >
      <q-tooltip class="bg-red" :offset="[10, 10]"> 下载 </q-tooltip></q-icon
    >
  </q-page>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getResult } from "src/api/api"; // 假设该 API 调用返回文件 URL

const loading = ref(false);
const htmlUrl = ref("");
const docUrl = ref("");
const handleDownload = async () => {
  loading.value = true;
  const resultResponse = {
    file_id: 7, // 动态设置 file_id
    project_id: 2, // 动态设置 project_id
  };

  try {
    // 在获取 URL 之前加上一个随机数或时间戳来避免缓存
    const cacheBuster = `?cb=${new Date().getTime()}`; // 使用当前时间戳作为缓存标识

    const response = await getResult(resultResponse);
    console.log(response);
    if (response.status === 200) {
      // 拼接带缓存清除标记的 URL
      htmlUrl.value = `${import.meta.env.VITE_BACKEND_URL}${
        response.data.html_url
      }${cacheBuster}`;
      docUrl.value = `${import.meta.env.VITE_BACKEND_URL}${
        response.data.doc_url
      }${cacheBuster}`;
      console.log("File URL received:", htmlUrl.value);
    } else {
      console.error("Error fetching file URL:", response.statusText);
    }
  } catch (error) {
    console.error("Error during file URL retrieval:", error);
  } finally {
    loading.value = false;
  }
};

const downloadFile = () => {
  if (docUrl.value) {
    const link = document.createElement("a");
    link.href = docUrl.value;
    link.download = "consult"; // 可以指定文件下载名称
    link.click();
  }
};

// 页面加载时自动获取文件 URL
onMounted(() => {
  handleDownload();
});
</script>

<style scoped>
.q-page {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.content-display {
  width: 100%;
  height: 100vh;
  border: none;
}

.download-icon {
  position: fixed;
  bottom: 20px;
  right: 20px;
  cursor: pointer;
}
</style>
